package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.CouponForm;
import com.springboot.cloud.demos.entity.param.CouponQueryParam;
import com.springboot.cloud.demos.entity.po.Coupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class CouponService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "conditionsFallback")
    public Result conditions(@RequestBody CouponQueryParam param) {
        return restTemplate.postForEntity("http://producer/coupon/conditions", param, Result.class).getBody();
    }

    public Result conditionsFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "couponFallback")
    public Result coupon(String couponId) {
        return restTemplate.getForEntity("http://producer/coupon/{couponId}", Result.class, couponId).getBody();
    }

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody CouponForm couponForm) {
        return restTemplate.postForEntity("http://producer/coupon", couponForm, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody CouponForm couponForm) {
        restTemplate.put("http://producer/coupon/{1}", couponForm, couponForm.getId());
        return Result.success();
    }

    @SentinelResource(fallback = "couponFallback")
    public void delete(String id) {
        restTemplate.delete("http://producer/coupon/{id}", Result.class, id);
    }

    public Result couponFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }
    public Result saveFallback(@RequestBody CouponForm couponForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result updateFallback(Coupon coupon) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }


}
